/*
 * @Author: jhw jiaxianshengye@gmail.com
 * @LastEditTime: 2025-07-31 11:36:39
 * @LastEditors: jhw
 * @Description: 文件描述
 */
// src/workers/excel.worker.js
import * as ExcelJS from 'exceljs'

self.onmessage = async (e) => {
  const { data, fileName } = e.data
  try {
    const workbook = new ExcelJS.Workbook()
    const worksheet = workbook.addWorksheet('Sheet2')

    // 添加表头
    const headers = Object.keys(data[0])
    worksheet.addRow(headers)

    // 添加数据行
    data.forEach((row) => {
      const values = headers.map((header) => row[header])
      worksheet.addRow(values)
    })

    // 生成 Excel Buffer
    const buffer = await workbook.xlsx.writeBuffer()

    const arrayBuffer = buffer.buffer

    // 返回结果给主线程
    self.postMessage(
      {
        status: 'success',
        arrayBuffer,
        fileName,
      },
      [arrayBuffer],
    )
  } catch (error) {
    self.postMessage({
      status: 'error',
      error: error.message,
    })
  }
}
